package me.sealer.spring_data.controller;

import me.sealer.spring_data.dao.PersonRepository;
import me.sealer.spring_data.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by sealer on 09-23-2017.
 */

@RestController
public class DataController {

    @Autowired
    PersonRepository personRepository;

    @RequestMapping("/save")
    public Person save(String name, String address, Integer age) {
        Person p = personRepository.save(new Person(null, name, age, address));
        return p;
    }

    @RequestMapping("/queryByAddress")
    public List<Person> q1(String address) {
        List<Person> people = personRepository.findByAddress(address);
        return people;
    }

    @RequestMapping("/queryByNameAndAddress1")
    public Person q2(String name, String address) {
        Person people = personRepository.findByNameAndAddress(name, address);
        return people;
    }

    @RequestMapping("/queryByNameAndAddress2")
    public Person q3(String name, String address) {
        Person people = personRepository.withNameAndAddressNamedQuery(name, address);
        return people;
    }

    @RequestMapping("/queryByNameAndAddress3")
    public Person q4(String name, String address) {
        Person people = personRepository.withNameAndAddressQuery(name, address);
        return people;
    }

    @RequestMapping("/sort")
    public List<Person> sort(String ascDesc, String field) {
        Sort.Direction s = Sort.Direction.ASC;
        if (field == null || (!"id".equals(field) && !"address".equals(field) && !"name".equals(field))) {
            field = "age";//默认年龄
        }
        if ("asc".equalsIgnoreCase(ascDesc)) {
            s = Sort.Direction.ASC;
        } else if ("desc".equalsIgnoreCase(ascDesc)) {
            s = Sort.Direction.DESC;
        }
        List<Person> people = personRepository.findAll(new Sort(s, field));
        return people;
    }

    @RequestMapping("/page")
    public Page<Person> page(String page, String size) {

        Integer iPage = 0;
        Integer iSize = 2;
        try {
            iPage = Integer.parseInt(page);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            iSize = Integer.parseInt(size);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Page<Person> pagePeople = personRepository.findAll(new PageRequest(iPage, iSize));
        return pagePeople;
    }
}
